<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\BaseController;
use app\index\model\GoodsImage;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use think\File;
use think\Image;

class Goods extends BaseController
{


    public function goods()
    {


        $cate_id = Request::get('cate_id','','trim,htmlspecialchars,strip_tags');
        $price_min = Request::get('price_min','','trim,htmlspecialchars,strip_tags');
        $price_max = Request::get('price_max','','trim,htmlspecialchars,strip_tags');
        $add_time_min = Request::get('add_time_min','','trim,htmlspecialchars,strip_tags');
        $add_time_max = Request::get('add_time_max','','trim,htmlspecialchars,strip_tags');
        $recommended = Request::get('recommended','2','trim,htmlspecialchars,strip_tags');
        $if_show = Request::get('if_show',[],'trim,htmlspecialchars,strip_tags');
        $goods_name = Request::get('goods_name','','trim,htmlspecialchars,strip_tags');
        $sj = Request::get('sj','','trim,htmlspecialchars,strip_tags');
        $get=Request::get();
        echo "<pre>";
        print_r($sj);
        echo "</pre>";

        $data=[
            'price_min'=>$price_min,
            'price_max'=>$price_max,
            'add_time_min'=>$add_time_min,
            'add_time_max'=>$add_time_max,
            'recommended'=>$recommended,
            'if_show'=>$if_show,
            'goods_name'=>$goods_name,
            'cate_id'=>$cate_id,
        ];


        $sp=\app\index\model\Goods::getGoods($data,$data,[],$sj);
        $cate=\app\index\model\Gcategory::getGcategory();





//            foreach ($sp as $k=>$v){
//                $sp[$k]['goods_name']=str_replace($goods_name,'<span style="color: red;font-weight: 900">'.$goods_name.'</span>',$v['goods_name']);
//            }



       $list=\app\index\model\Goods::getGoods($data,$get);
//        if ($get['page']&&$get['page']>$list->currentPage()){
//            $list = \app\index\model\Goods::getGoods($data,$get,$list->currentPage());
//        }



        $empty="<tr><td colspan='8'>暂无数据</td></tr>";
        View::assign($get);
        View::assign('empty',$empty);
        View::assign('data',$data);
        View::assign('list',$list);
        View::assign('cate_id',$cate_id);
        return View::fetch('',['sp'=>$sp,'cate'=>$cate]);
    }

    protected function moveTempFile($oldfile,$newfile,$prefix='storage/'){
        try{

            $arr = explode('/',$newfile);
            unset($arr[count($arr)-1]);
            $dir = implode('/',$arr);
            $dir = $prefix.$dir;

            if(!is_dir($dir)) {
                mkdir($dir, 777, true);
            }
            copy($prefix.$oldfile,$prefix.$newfile);
            $font = PROJECT_ROOT_PATH.'/public/font/simfang.ttf';
           if(is_file($prefix.$newfile)){
               Image::open($prefix.$newfile)
                   ->text($prefix.$newfile,$font,50,'#FF0000')
                   ->save($prefix.$newfile);
           }

            // 删除原临时文件
            return unlink($prefix.$oldfile);
        }catch (\Exception $e){
            return false;
        }

    }

    public function goods_add(){

        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');
            $images = Request::file('');
            if ($_FILES['default_image']['error']!=4){
                $images = Request::file('');
            }else{
                $this->error('没有文件上传');
            }

            if ($_FILES['image_url']['error']!=4){
                $images = Request::file('');
            }else{
                $this->error('没有文件上传');
            }

            if(isset($images['default_image'])) {

                $result = $this->upload_singlefile($images['default_image'], 'default_image');
                $img=['default_image'=>$images['default_image']];
                try{
                    validate(\app\validate\Goods::class)->scene('upload')->check($img);
                }catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }

                if (false === $result) {
                    $this->error();
                }

                list($dir,$filename)   = explode('/',$result,2);
                $post['default_image'] = "data/upload/" . $filename;
            }


            if(isset($images['image_url']) && !empty($images['image_url'])){
                try{
                    foreach($images['image_url'] as $image){
                        $data = ['image_url'=>$image];

                        validate(\app\validate\Goods::class)->scene('upload')->check($data);

                        $savename = \think\facade\Filesystem::putFile('up',$image,'get_uploadfile_name');
                        $savename = str_replace('\\','/',$savename);

                        list($dir,$filename) = explode('/',$savename,2);
                        $post['image_url'][] = "data/upload/" . $filename;
                    }
                }catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
            }






            //返回数据
            $jumpPath='';
            if('1'==$post['button'])   $jumpPath = url('goods');
            if ('2'==$post['button'])  $jumpPath = url('goods_add');

            $goodsObj = new \app\index\model\Goods();
            $result = $goodsObj->add($post);
            $post['goods_id']=$goodsObj->getInsertId();
//            $post['image_url']= implode(',',$post['image_url']);
//            $banner= new \app\index\model\GoodsImage();
//            $result1 = $banner->add($post);

            //如果添加成功进行的处理

            if(isset($post['default_image']) && $result){

                $oldfile = str_replace('data/upload/','up/',$post['default_image']);

                $this->moveTempFile($oldfile,$post['default_image']);


            }

            if(isset($post['image_url']) && $result){
//                $post['image_url']= explode(',',$post['image_url']);
                foreach($post['image_url'] as $value){

                    $oldfile = str_replace('data/upload/','up/',$value);

                    $this->moveTempFile($oldfile,$value);

                }
            }




            if($result){
                //提交事务
                Db::commit();
                $this->success("成功！".$goodsObj->getInsertId(),$jumpPath);


            }else{
                // 回滚事务
                Db::rollback();
                $this->error("失败！原因：".$goodsObj->getError());


            }

        }else{
            $cate_id = Request::get('cate_id','','trim,htmlspecialchars,strip_tags');
            View::assign('cate_id',$cate_id);

            $cate=\app\index\model\Gcategory::getGcategory();
            View::assign('cate',$cate);

            $brand=\app\index\model\Brand::getBrand([],[],true);
            View::assign('brand',$brand);
            return View::fetch();
        }
    }

    //修改
    public function goods_edit(){
        $param=Request::param('param',[],'trim,htmlspecialchars,strip_tags');
        $cate_id = Request::get('cate_id','','trim,htmlspecialchars,strip_tags');
        View::assign('cate_id',$cate_id);

        $cate=\app\index\model\Gcategory::getGcategory();
        View::assign('cate',$cate);

        $brand=\app\index\model\Brand::getBrand([],[],true);
        View::assign('brand1',$brand);

        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');

            $goods_logo_old=Request::post('goods_logo_old','','');
            if ($_FILES['default_image']['error']!=4){
                $default_image=Request::file('default_image','');
            }else{
                $this->error('没有文件上传');
            }


            Db::startTrans();
            try{
                    validate(\app\validate\Goods::class)->scene('edit')->check($post);
                    // 验证通过 执行上传
                    $savename = \think\facade\Filesystem::disk('public')->putFile('data/upload/',$default_image,'get_uploadfile_name');
                    $post['default_image']=str_replace('\\','/',$savename);



            }catch (\think\exception\ValidateException $e){
                $this->error($e->getMessage());
            }catch (\Exception $e){

            }


            $arr=explode('/',$goods_logo_old);
            unset($arr[count($arr)-1]);
            $dir = implode('/',$arr);
            if (is_dir($dir)){
                unlink('storage/'.$goods_logo_old);
            }


            $goodsObj = new \app\index\model\Goods();
            $result = $goodsObj->edit($post);

            if($result){

                $font = PROJECT_ROOT_PATH.'/public/font/simfang.ttf';
                Image::open('storage/'.$post['default_image'])
                    ->text($post['default_image'],$font,50,'#FF0000')
                    ->save('storage/'.$post['default_image']);

                //提交事务
                Db::commit();
                $this->success('修改成功！',url('goods',$param));
            }else{
                // 回滚事务
                Db::rollback();
                $this->error('修改失败！');
            }


        }else{
            // 显示修改的页面
            $id = Request::get('id','','trim,htmlspecialchars,strip_tags');

            $goodsObj = \app\index\model\Goods::find($id)->getData();
            if(empty($goodsObj)){
                $this->error('参数错误！',url('goods'));
            }

            return View::fetch('',$goodsObj);
        }

    }
    //软删除
    public function del(){
        $id =Request::get('id','','');
        try{
            \app\index\model\Goods::destroy($id);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('删除成功！',getenv("HTTP_REFERER"));

    }

    //回收站
    public function goods_recycle(){


       $db= Db::table('ecm_goods')->where('del','>',0)
            ->select()
            ->toArray();


        $empty="<tr><td colspan='8'>暂无数据</td></tr>";

        View::assign('empty',$empty);
        return View::fetch('',['db'=>$db]);
    }
    //回收数据
    public function recycle(){
        $id =Request::get('id','','');

        try{
            $user = \app\index\model\Goods::onlyTrashed()->find($id);
            $user->restore();
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('恢复成功！');

    }

    //物理删除
    public function real_del(){
        $id =Request::get('id','','');


        $image=Db::table('ecm_goods')->field('default_image')->whereIn('goods_id',$id)->select()->toArray();


        try{
            $id=explode(',',$id);

                 $res=   \app\index\model\Goods::delgoods($id);

                if ($res){
                    foreach ($image as $k=>$vo){
                        $arr=explode('/',$vo['default_image']);
                        unset($arr[count($arr)-1]);
                        $dir = implode('/',$arr);


                        if (is_dir('storage/'.$dir)){
                            unlink('storage/'.$vo['default_image']);
                        }
                    }
                }else{
                    $this->error('删除失败');
                }





        }catch (\Exception $e){
            $this->error($e->getMessage());

        }
        $this->success('删除成功!',getenv("HTTP_REFERER"));
    }

    //多删
    public function all_del(){
        $id =Request::get('id',"",'');

        Db::startTrans();

        try{
            $id=explode(',',$id);
            \app\index\model\Goods::destroy($id);

            //提交事务
            Db::commit();

        }catch (\Exception $e){
            $this->error($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        $this->success('删除成功!',getenv("HTTP_REFERER"));

    }

    protected function upload_singlefile($file,$input_name){
        if(isset($file) && $file instanceof File){
            try{
                $data = [$input_name=>$file];
                //validate([$input_name=>$this->rule])->scene('upload')->check($data);
                validate(\app\validate\Goods::class)->scene('upload')->check($data);

                $savename = \think\facade\Filesystem::putFile('up',$file,'get_uploadfile_name');

                return str_replace('\\','/',$savename);
            }catch (\think\exception\ValidateException $e) {
                $this->error = $e->getMessage();
                return false;
            }
        }

    }





//<!--<script type="text/javascript">-->
//<!--if(<{$aa}>=='kong')-->
//<!--$('.fenlei').click(function () {-->
//    <!--console.log(1);-->
//    <!--var that=$(this).html();-->
//    <!--that.empty();-->
//    <!--that.push(<span href="cate.html?id=<{$v['cate_id']}>"  ><{$v['cate_name']}></span>);-->
//    <!--alert('没有数据');-->
//    <!--history.back();-->
//<!--})-->
//<!--</script>-->










}
